package com.miyu.rabbitmq.service;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.miyu.rabbitmq.config.MessageListenerImpl;
import com.miyu.rabbitmq.config.MqUtils;
import com.miyu.rabbitmq.config.MqVo;
import com.miyu.rabbitmq.dao.SysMqConfigDao;
import com.miyu.rabbitmq.pojo.SysMqConfig;
import com.miyu.rabbitmq.utils.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@RabbitListener(queues = {"交换机名称"})
public class RabbitServiceImpl implements RabbitService {
    private final MqUtils mqUtils;
    private final SysMqConfigDao dao;

    private final SimpleMessageListenerContainer container;
    private final MessageListenerImpl message;

    @Override
    public JSONObject add(SysMqConfig mqConfig) {
        //写入数据库
        SysMqConfig save = dao.save(mqConfig);
        //判断是否写入成功
        if (StrUtil.isNotBlank(save.getMqId())) {
            //判断是否启用消息队列
            status(mqConfig);
        }
        return R.result("101");
    }

    @Override
    public JSONObject update(SysMqConfig mqConfig) {
        //查询数据库现存信息
        SysMqConfig byId = dao.findById(mqConfig.getMqId()).orElse(null);
        //修改数据
        SysMqConfig sysMqConfig = dao.saveAndFlush(mqConfig);
        //boolean b = updateById(mqConfig);
        //判断是否修改成功
        //  if (b) {
        //删除消息队列
        addOrDelMq(byId, 0);
        //判断是否启用消息队列
        status(mqConfig);
        //  }
        return R.result("101");
    }

    /**
     * 状态位为开启时,消息队列创建方法封装
     * @param mqConfig
     */
    private void status(SysMqConfig mqConfig) {
        if ("0".equals(mqConfig.getStatus())) {
            //创建消息队列
            addOrDelMq(mqConfig, 0);
        }
    }

    /**
     * 新增队列方法封装
     * @param mqConfig
     */
    public void addOrDelMq(SysMqConfig mqConfig, int type){
        mqUtils.mqOperate(
                MqVo
                    .builder()
                    .exchangeType(mqConfig.getExchangeType())
                    .queueName(mqConfig.getQueueName())
                    .exchangeName(mqConfig.getExchangeName())
                    .binding(mqConfig.getBinding())
                    .delayType(mqConfig.getDelayType())
                    .type(type)
                    .build()
        );
    }

    /**
     * 删除消息队列
     * @param mqIds
     * @return
     */
    @Override
    public JSONObject delete(String[] mqIds) {
        Boolean b = false;
        for (String mqId : mqIds) {
            //查询消息队列信息
            SysMqConfig mqConfig = dao.findById(mqId).orElse(null);
            //删除消息队列
            if(mqConfig!=null) {
                //removeById(mqId);
                dao.delete(mqConfig);
                addOrDelMq(mqConfig, 1);
            }
            //判断消息队列是否删除成功
            //  if (b) {
            //删除消息队列
            //   addOrDelMq(mqConfig, 1);
            // }
        }
        return R.result("101");
    }


    private final RabbitTemplate rabbitTemplate;
    /**
     * @param params
     * @return
     */
    @Override
    public JSONObject sendMessage(JSONObject params) {
        String message = params.getString("message");
        String routKey = params.getString("queueName");
        String exchangeName = params.getString("exchangeName");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        jsonObject.put("queueName", routKey);
        JSONObject.toJSONString(jsonObject);
        System.out.println("发送时打印消息内容："+rabbitTemplate.getUUID());
        rabbitTemplate.convertAndSend(exchangeName,"2", JSONObject.toJSONString(jsonObject),new CorrelationData(rabbitTemplate.getUUID()));
        return R.result("101");
    }



    /**
     * @param params
     */
    @Override
    public void recieveMessage(JSONObject params) {
        //获取当前监听的队列名称
        String queueName=params.getString("queueName");
        String[] strings = container.getQueueNames();
        List<String> list = Arrays.asList(strings);
//        container.removeQueueNames(list);
        //     container.removeQueueNames(strings.toString());
        if (!list.contains(queueName)) {
            container.addQueueNames(queueName);

            container.setPrefetchCount(1);
            container.setConcurrentConsumers(5);
            //设置消息监听处理类
            container.setMessageListener(message);

        }else{
            container.addQueueNames(queueName);
            container.setPrefetchCount(1);
            container.setConcurrentConsumers(5);
            container.setAcknowledgeMode(AcknowledgeMode.AUTO);
            container.setMessageListener(message);

        }
    }

    /**
     * 查询系统mqconfig
     *
     * @param params
     * @return
     */
    @Override
    public List<SysMqConfig> querySysMqConfig(JSONObject params) {
        List<SysMqConfig> reslut  = dao.findAll();
        return reslut;
    }
}
